import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {AtSearchBar} from 'taro-ui'
import {connect} from 'react-redux';
import {View} from '@tarojs/components'
import {Good, CityLocation} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {IDENTITY_IS_SELLER, SEARCH_GOODS} from '../../constants/api'
import BigGoodsBox from '../../components/big-goods-box/big-goods-box'
import {autoLocation, setCity} from '../../actions/location'
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './search.scss'

interface stateType {
  searchResult: Good[]
  searchText: string
  labelText: string
  isUser: boolean
}


type PageStateProps = {
  location: CityLocation
}

type PageDispatchProps = {
  setCity: (city: CityLocation) => void
  autoLocation: (city: CityLocation) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Search {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({
  setCity(city) {
    dispatch(setCity(city))
  },
  autoLocation(city) {
    dispatch(autoLocation(city))
  }
}))

class Search extends Component {
  state: stateType = {
    searchResult: [],
    searchText: '',
    labelText: '',
    isUser: true
  }
  page = 1
  canMore = true

  searchConfirm() {
    this.page = 1
    this.setState({searchResult: ''}, () => {
      this.search(this.page)
    })
  }

  async componentDidShow() {
    vcmonitor(this)
    let isUser = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      isUser = !identityIsSeller.isSeller
    }
    this.setState({isUser})
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    if (Taro.getCurrentInstance().router.params.key) {
      this.setState({searchText: Taro.getCurrentInstance().router.params.key}, async () => {
        await this.search(this.page)
      })
    } else {
      if (Taro.getCurrentInstance().router.params.label) {
        Taro.setNavigationBarTitle({
          title: Taro.getCurrentInstance().router.params.label
        })
        this.setState({labelText: Taro.getCurrentInstance().router.params.label}, async () => {
          await this.search(this.page)
        })
      }
    }
  }

  async onReachBottom() {
    if (this.canMore) {
      this.page++
      await this.search(this.page)
    }
  }

  async search(page) {
    Taro.showLoading({title: '加载中...'})
    const ret = await this.getSearchData(page);
    Taro.hideLoading()
    if (ret && ret.length > 0) {
      if (page === 1) {
        this.setState({searchResult: ret})
      } else if (page > 1) {
        const oldData = this.state.searchResult;
        this.setState({searchResult: [...oldData, ...ret]})
      }
    } else {
      this.canMore = false
      Taro.showToast({
        title: '没有更多数据了',
        icon: 'none'
      })
    }
  }

  async getSearchData(page) {
    if (typeof page != "number") {
      page = this.page + 1
    }
    const {searchText, labelText} = this.state
    if (searchText || labelText) {
      const data = {
        p: page,
        areaId: this.props.location.region_id
      }
      if (searchText) {
        data['k'] = searchText
      }
      if (labelText) {
        data['label'] = labelText
      }
      const result = await http.post<Good[]>(SEARCH_GOODS, data)
      if (!result) {
        return false;
      }
      this.canMore = result.length >= 10;
      return result
    } else {
      Taro.showToast({
        title: '搜索词不能为空',
        icon: 'none'
      })
    }
    return false
  }

  input(value) {
    if (value) {
      this.setState({searchText: value})
    }
  }

  clearSearch() {
    this.setState({searchText: '', searchResult: []})
  }

  render() {
    const {searchResult, searchText, labelText, isUser} = this.state
    return (
      <View className='search-root'>
        <GzhAuth />
        {!labelText &&
        <AtSearchBar focus={!Taro.getCurrentInstance().router.params.key} onConfirm={this.searchConfirm.bind(this)}
          onClear={this.clearSearch.bind(this)} onActionClick={this.searchConfirm.bind(this)}
          value={searchText} onChange={this.input.bind(this)} placeholder='搜索关键词'
        />}
        {searchResult.length > 0 && <View className='search-result'>
          <BigGoodsBox isUser={isUser} data={searchResult} />
        </View>}
      </View>
    )
  }
}

export default Search as ComponentClass<PageOwnProps, PageState>
